package net.lab1024.sa.admin.module.business.yuqing.util;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.yuqing.constant.YuqingConst;
import net.lab1024.sa.admin.module.business.yuqing.dao.NewsArticleDao;
import net.lab1024.sa.admin.module.business.yuqing.domain.entity.NewsArticleEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 新闻数据导入工具类
 *
 * @Author 1024创新实验室: 卓大
 * @Date 2025-01-15 10:00:00
 * @Wechat zhuda1024
 * @Email lab1024@163.com
 * @Copyright  <a href="https://1024lab.net">1024创新实验室</a>
 */
@Slf4j
@Component
public class NewsImportUtil {

    @Autowired
    private NewsArticleDao newsArticleDao;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final String[] SENTIMENTS = {"POSITIVE", "NEGATIVE", "NEUTRAL"};
    private static final Random RANDOM = new Random();

    /**
     * 从CSV文件导入新闻数据
     */
    public String importNewsFromCsv(String filePath) {
        try {
            List<NewsArticleEntity> articleList = parseCsvFile(filePath);
            if (articleList.isEmpty()) {
                return "没有找到有效的数据";
            }

            // 批量保存到数据库
            int successCount = 0;
            for (NewsArticleEntity article : articleList) {
                try {
                    newsArticleDao.insert(article);
                    successCount++;
                } catch (Exception e) {
                    log.error("保存文章失败：{}", article.getTitle(), e);
                }
            }

            return String.format("成功导入 %d 条数据，总共 %d 条数据", successCount, articleList.size());

        } catch (Exception e) {
            log.error("导入数据失败", e);
            return "导入失败：" + e.getMessage();
        }
    }

    /**
     * 解析CSV文件
     */
    private List<NewsArticleEntity> parseCsvFile(String filePath) throws IOException {
        List<NewsArticleEntity> articleList = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(filePath)) {
            // 读取所有内容
            String content = new String(fis.readAllBytes(), "UTF-8");
            
            // 移除BOM
            if (content.startsWith("\uFEFF")) {
                content = content.substring(1);
            }
            
            String[] lines = content.split("\n");
            
            if (lines.length < 2) {
                return articleList;
            }

            // 跳过标题行，从第二行开始解析
            for (int i = 1; i < lines.length; i++) {
                String line = lines[i].trim();
                if (StringUtils.isBlank(line)) {
                    continue;
                }

                try {
                    NewsArticleEntity article = parseCsvLine(line);
                    if (article != null) {
                        articleList.add(article);
                    }
                } catch (Exception e) {
                    log.error("解析第{}行数据失败：{}", i + 1, line, e);
                }
            }
        }

        return articleList;
    }

    /**
     * 解析CSV行数据
     */
    private NewsArticleEntity parseCsvLine(String line) {
        // 解析CSV行：title,time,text,author,url
        String[] fields = parseCSVLine(line);
        
        if (fields.length < 5) {
            log.warn("数据格式不正确，跳过：{}", line);
            return null;
        }

        NewsArticleEntity article = new NewsArticleEntity();
        
        // 设置标题
        article.setTitle(cleanField(fields[0]));
        
        // 设置发布时间
        try {
            String timeStr = cleanField(fields[1]);
            LocalDateTime publishTime = LocalDateTime.parse(timeStr + "T00:00:00");
            article.setPublishTime(publishTime);
        } catch (DateTimeParseException e) {
            log.warn("时间格式解析失败：{}，使用当前时间", fields[1]);
            article.setPublishTime(LocalDateTime.now());
        }
        
        // 设置内容
        article.setContent(cleanField(fields[2]));
        
        // 设置作者
        article.setAuthor(cleanField(fields[3]));
        
        // 设置URL
        article.setSourceUrl(cleanField(fields[4]));
        
        // 随机设置情感倾向
        article.setSentiment(SENTIMENTS[RANDOM.nextInt(SENTIMENTS.length)]);
        
        // 设置默认值
        article.setViewCount(0);
        article.setDeletedFlag(false);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        return article;
    }

    /**
     * 清理字段内容
     */
    private String cleanField(String field) {
        if (field == null) {
            return "";
        }
        
        field = field.trim();
        if (field.startsWith("\"") && field.endsWith("\"")) {
            field = field.substring(1, field.length() - 1);
        }
        
        return field;
    }

    /**
     * 简单CSV解析
     */
    private String[] parseCSVLine(String line) {
        List<String> result = new ArrayList<>();
        boolean inQuotes = false;
        StringBuilder current = new StringBuilder();
        
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            
            if (c == '"') {
                inQuotes = !inQuotes;
            } else if (c == ',' && !inQuotes) {
                result.add(current.toString());
                current = new StringBuilder();
            } else {
                current.append(c);
            }
        }
        
        result.add(current.toString());
        return result.toArray(new String[0]);
    }
} 